package com.googlecode.jpocketmod;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.swing.UIManager;

/**
 *
 * @author David Sosby
 */
public class ApplicationProperties {
	private static Properties properties;
	private static final File propertiesFile = new File(System.getProperty("user.home") + File.separator + "JPocketModSettings.xml");
	private static ApplicationProperties instance = new ApplicationProperties();

	/**
	* Creates a new instance of ApplicationProperties
	*/
	private ApplicationProperties() {
		properties = new Properties(getDefaultProperties());
		loadProperties();
	}

	public void saveProperties()  {
		try  {
			FileOutputStream propertiesFileOutput = new FileOutputStream(propertiesFile);
			properties.storeToXML(propertiesFileOutput, "--NO COMMENT--");
			propertiesFileOutput.close();
		}
		catch (Exception ex)  {
			String msg = "Generic exception storing properties file: " + ex.getMessage();
		}
	}

	private Properties getDefaultProperties()  {
		Properties defaultProperties = new Properties();

		defaultProperties.setProperty("UI.LookAndFeel", UIManager.getSystemLookAndFeelClassName());
		defaultProperties.setProperty("UI.WindowWidth", "420");
		defaultProperties.setProperty("UI.WindowHeight", "600");
		defaultProperties.setProperty("UI.WindowLocX", "10");
		defaultProperties.setProperty("UI.WindowLocY", "10");
		
		defaultProperties.setProperty("Settings.StorageFolder", System.getProperty("user.home") + File.separator + ".jpocketmod" + File.separator);
		defaultProperties.setProperty("Settings.PageFolder", defaultProperties.getProperty("Settings.StorageFolder") + "pages");
		defaultProperties.setProperty("Settings.PluginsFolder", defaultProperties.getProperty("Settings.StorageFolder") + "plugins");

		return defaultProperties;
	}

	private void loadProperties()  {
		if (propertiesFile.exists())  {
			try  {
				FileInputStream propertiesFileInput = new FileInputStream(propertiesFile);
				properties.loadFromXML(propertiesFileInput);
				propertiesFileInput.close();
			}
			catch (IOException ioe)  {
				String msg = "Error reading properties file: " + ioe.getMessage();
			}
			catch (Exception ex)  {
				String msg = "Generic exception reading properties file: " + ex.getMessage();
			}
		}
	}

	public static ApplicationProperties getInstance()  {  return instance;  }

	public String getProperty(String key)  {
		return properties.getProperty(key);
	}

	public Object setProperty(String key, String value)  {
		return properties.setProperty(key, value);
	}

	public boolean contains(String key)  {
		return properties.contains(key);
	}
}
